#coding=utf-8

import time
import md5
from conf import settings
import os
from tornado.httputil import HTTPFile

def _getpath():
    t = time.time()
    t = md5.md5(str(t)).hexdigest()
    y = str(time.localtime().tm_year)
    m = str(time.localtime().tm_mon)
    d = str(time.localtime().tm_mday)
    h = str(time.localtime().tm_hour)

    path = '/'.join([y, m, d, h, t])

    return path

def save(f):
    path = settings.UPLOAD_PATH
    if type(f) == HTTPFile:
        filename = f['filename']
        if len(filename.split('.')) > 1:
            path = settings.UPLOAD_PATH + _getpath() + "." + filename.split('.')[-1]
        else:
            path = settings.UPLOAD_PATH + _getpath()
        
        try:
            os.makedirs('/'.join(path.split('/')[0:-1]))
        except Exception, e:
            print e
        fil = open(path, 'w')
        fil.write(f['body'])
        fil.close()
    elif type(f) == str:
        if len(filename.split('.')) > 1:
            path = settings.UPLOAD_PATH + _getpath() + "." + f.split('.')[-1]
        else:
            path = settings.UPLOAD_PATH + _getpath()
        try:
            os.makedirs('/'.join(path.split('/')[0:-1]))
        except Exception, e:
            pass
        open(path, "wb").write(open(f, "rb").read())

    return "/upload/" + path.split(settings.UPLOAD_PATH)[1], path


from PIL import Image

class img(object):
        
    @staticmethod
    def crop(imgpath, savepath, left, top, width, height, dw, dh):
        img = Image.open(imgpath)
        size = img.size
        sw = float(size[0]) / float(width)
        sh = float(size[1]) / float(height)
        left = float(sw) * float(left)
        top = float(sh) * float(top)
        dw = float(sw) * float(dw)
        dh = float(sh) * float(dh)

        # print left
        # print top
        # print dw
        # print dh

        fimg = img.crop((int(left), int(top), int(dw+left), int(dh+top)))
        fimg.save(savepath)

    @staticmethod
    def thumbnail(imgpath, savepath, w=320, h=320):
        img = Image.open(imgpath)
        img.thumbnail((w, h), Image.ANTIALIAS)
        img.save(savepath)
